import 'package:flutter/material.dart';
import '../../utils/G.dart';

class Address extends StatefulWidget {
  const Address({Key? key}) : super(key: key);

  @override
  _AddressState createState() => _AddressState();
}

class _AddressState extends State<Address> {
  List list = [];
  int defaultAddressId = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('收货地址列表'),
        centerTitle: true,
      ),
      body: FutureBuilder(
          future: G.api.address.list(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              var res = snapshot.data as Map;
              if (res['status'] == 200) {
                list = res['data'];
                // 获取默认收货地址的 ID
                defaultAddressId = _getDefaultAddressId();

                return Container(
                  height: G.height,
                  child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      physics: const BouncingScrollPhysics(),
                      child: AddressList(
                          list: list, defaultAddressId: defaultAddressId)),
                );
              } else {
                // 报错
                G.error('接口请求失败');
              }
            } else if (snapshot.hasError) {
              return Center(
                child: Text("${snapshot.error}"),
              );
            }

            return G.loader();
          }),
      bottomNavigationBar: _addAddress(),
    );
  }

  int _getDefaultAddressId() {
    int target = 0;
    list.forEach((element) {
      if (element['is_default'] == 1) {
        target = element['id'];
      }
    });

    return target;
  }

  Widget _addAddress() {
    return Container(
      padding: const EdgeInsets.all(30),
      child: ElevatedButton(
          onPressed: () {
            // 跳转到添加收获地址的页面
            G.router.navigateTo(context, '/address_add');
          },
          child: const Text('新增收获地址'),
          style: ButtonStyle(
            shape: MaterialStateProperty.all(const StadiumBorder()),
            elevation: MaterialStateProperty.all(10),
            minimumSize: MaterialStateProperty.all(Size(G.width - 100, 50)),
          )),
    );
  }
}

// 收货地址列表组件
class AddressList extends StatefulWidget {
  List list;
  int defaultAddressId;
  AddressList(
      {Key? key, required List this.list, required int this.defaultAddressId})
      : super(key: key);

  @override
  _AddressListState createState() => _AddressListState();
}

class _AddressListState extends State<AddressList> {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: widget.list.isNotEmpty
          ? widget.list.map<Widget>((e) {
              return _renderAddressItem(e);
            }).toList()
          : [
              const Center(
                child: Text('空空如也~'),
              )
            ],
    );
  }

  Widget _renderAddressItem(Map item) {
    return ListTile(
      leading: Radio(
        value: item['id'],
        groupValue: widget.defaultAddressId,
        onChanged: (dynamic value) async {
          // 设置默认地址
          var res = await G.api.address.setDefault(value);
          if (res['status'] == 200) {
            setState(() {
              widget.defaultAddressId = value;
            });
            G.success('设置成功');
          } else {
            G.error('设置失败');
          }
        },
      ),
      title: Text('收货人：' +
          item['real_name'].toString() +
          ", " +
          item['phone'].toString()),
      subtitle: Text('地址：' +
          item['province'] +
          item['city'] +
          item['district'] +
          item['detail']),
      trailing: InkWell(
          child: const Icon(Icons.delete_forever),
          onTap: () async {
            // 删除当前收货地址
            var res = await G.api.address.del(item['id']);
            if (res['status'] == 200) {
              setState(() {
                widget.list
                    .removeWhere((element) => element['id'] == item['id']);
              });
              G.success('删除成功');
            } else {
              G.error('删除失败');
            }
          }),
    );
  }
}
